﻿using System;
using System.Collections;
using UnityEngine;


public delegate void Response(ErrorCode errorCode);

public delegate void LoginResponse(ErrorCode errorCode, AccountInfo accountInfo);

[Serializable]
public class AccountInfo
{
	public string Phone;
	public string Password;
	public string UserName;
	public int	Age;
	public byte Sex;
	public string RegisterTime;
	public string LastLoginTime;
}

public class Request {

	public static string baseurl = "https://www.poppintech.com/index.php/";

	public static string RegisterURL { get { return baseurl + "useradd"; } }
	public static string LoginURL { get { return baseurl + "userget"; } }

	public class RegResopnseData
	{
		public ErrorCode ErrorCode;
	}

	public static IEnumerator RegisterAccount(AccountInfo registerInfo, Response resp)
	{
		WWWForm form = new WWWForm();
		form.AddField("phone", registerInfo.Phone);
		form.AddField("password", registerInfo.Password);
		form.AddField("username", registerInfo.UserName);
		form.AddField("age", registerInfo.Age);
		form.AddField("sex", registerInfo.Sex);

		WWW www = new WWW(RegisterURL, form);
		yield return www;

		RegResopnseData errorCode = null;
		if (!string.IsNullOrEmpty(www.error))
		{
			Debug.LogError(www.error);
		}
		else
		{
			errorCode = JsonUtility.FromJson<RegResopnseData>(www.text);
		}
		www.Dispose();

		resp(errorCode == null ? ErrorCode.Fail : errorCode.ErrorCode);
	}

	public class LoginResponseData
	{
		public ErrorCode ErrorCode;
		public AccountInfo AccountInfo;
	}

	public static IEnumerator Login(string phone, string password, LoginResponse loginResponse)
	{ 
		WWWForm form = new WWWForm();
		form.AddField("phone", phone);
		form.AddField("password", password);

		string loginURL = LoginURL;
		WWW www = new WWW(LoginURL, form);
		yield return www;

		ErrorCode errorCode = ErrorCode.Fail;
		AccountInfo accountInfo = null;
		if (!string.IsNullOrEmpty(www.error))
		{
			Debug.LogError(www.error);
		}
		else
		{
			LoginResponseData loginResponseData = JsonUtility.FromJson<LoginResponseData>(www.text);
			if (loginResponseData != null)
			{
				errorCode = loginResponseData.ErrorCode;
				accountInfo = loginResponseData.AccountInfo;
			}
		}
		www.Dispose();

		loginResponse(errorCode, accountInfo);
	}
}
